package com.tos.second.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tos.second.common.basecontext.BaseContext;
import com.tos.second.common.constant.MessageConstant;
import com.tos.second.common.exception.BaseException;
import com.tos.second.common.exception.BuyException;
import com.tos.second.dto.OrdersDto;
import com.tos.second.entity.Goods;
import com.tos.second.entity.Orders;
import com.tos.second.entity.User;
import com.tos.second.mapper.GoodsMapper;
import com.tos.second.mapper.OrdersMapper;
import com.tos.second.mapper.UserMapper;
import com.tos.second.service.GoodsService;
import com.tos.second.service.OrdersService;
import com.tos.second.vo.OrdersHistoryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {


    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserMapper userMapper;
    /**
     * 获取用户历史订单
     *
     * @return
     */
    @Override
    public List<OrdersHistoryVo> getOrdersHistory() {
        // 获取当前登录用户的id
        Long currentId = BaseContext.getCurrentId();
        //创造查询条件
//        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(Orders::getBuyerId, currentId);
        //获取用户历史订单
        List<Orders> list = ordersMapper.getMyBuyList(currentId);
        //进行stream流创造
        return list.stream().map(item -> {
            OrdersHistoryVo ordersHistoryVo = new OrdersHistoryVo();
            //复制基本相同属性
            BeanUtils.copyProperties(item, ordersHistoryVo);
            //查询其他数据，根据goodsId查询
            Long goodsId = item.getGoodsId();
            Goods byId = goodsMapper.getGoodsById(goodsId);
            if (byId == null) {
                ordersHistoryVo.setGoodsName(null);
                ordersHistoryVo.setImage(null);
                ordersHistoryVo.setGoodsDescription(null);
            }
            //赋值属性
            else {
                ordersHistoryVo.setGoodsName(byId.getName());
                ordersHistoryVo.setImage(byId.getImage());
                ordersHistoryVo.setGoodsDescription(byId.getDescription());
            }
            return ordersHistoryVo;
        }).toList();
    }

    @Override
    public void deleteOrder(Long id) {
        Long number =id;
        //获取买家 id
        Long buyerId = BaseContext.getCurrentId();
        ordersMapper.removeById(id);
    }

    @Override
    public List<OrdersHistoryVo> getSellerOrders() {
        Long currentId = BaseContext.getCurrentId();
        List<OrdersHistoryVo> ordersHistoryVoList = ordersMapper.getMySellList(currentId);
        return ordersHistoryVoList;
    }

    /**
     * 提交订单
     *
     * @param ordersDto
     */
//    @Override
//    public void submit(OrdersDto ordersDto){
//        Goods goods = goodsMapper.getGoodsById(id);
//        //判断是否有商品
//        if (goods == null || goods.getStatus() != 1) {
//            throw new BuyException(MessageConstant.GOODS_NOT_EXIT);
//        }
//        //获取商品中的卖家
//        Long sellerId = goods.getCreateUser();
//        //查询数据库
//        User sellerUser = userMapper.getById(sellerId);
//        //获得买家id，即当前登录id
//        Long buyerId = BaseContext.getCurrentId();
//        if (buyerId == null){
//            throw new BuyException(MessageConstant.USER_NOT_LOGIN);
//        }
//        //判断是否为同一人
//        if (sellerId.equals(buyerId)) {
//            throw new BuyException(MessageConstant.CAN_NOT_BUY_YOURSELF);
//        }
//        //如果不是同一人，获得买家数据库
//        User buyerUser = userMapper.getById(buyerId);
//        //获取商品价格和用户余额
//        BigDecimal price = goods.getPrice();
//        BigDecimal balance = buyerUser.getBalance();
//
//        //判断余额是否足够
//        if (balance.compareTo(price) < 0) {
//            throw new BuyException(MessageConstant.BALANCE_NOT_ENOUGH);
//        }
//        deleteRedisCaches();
//        // 生成订单号
//        String number = String.valueOf(System.currentTimeMillis());
//
//        // 创建订单
//        Orders orders = Orders.builder()
//                .amount(price)
//                .goodsId(id)
//                .buyerName(buyerUser.getName())
//                .sellerName(sellerUser.getName())
//                .orderTime(LocalDateTime.now())
//                .description(goodsBuyDto.getDescription())
//                .number(number)
//                .buyerId(buyerId)
//                .sellerId(sellerId)
//                .categoryId(goods.getCategoryId())
//                .status(1) // 设置订单状态为1（已下单）
//                .build();
//
//        //向数据库中插入订单数据
////        ordersService.save(orders);
//        ordersMapper.saveOrder(orders);
//        //更新余额
//        buyerUser.setBalance(balance.subtract(price));
//        //更新数据库中的商品status为2
//        goods.setStatus(2);
//        updateById(goods);
//        //卖家余额增加
//        sellerUser.setBalance(sellerUser.getBalance().add(price));
////更新数据库中的余额
////        userService.updateById(buyerUser);
//        userMapper.updateUser(buyerUser);
//        //更新数据库中的余额
////        userService.updateById(sellerUser);
//        userMapper.updateUser(sellerUser);
//
//
//        deleteRedisCaches();//删除redis缓存
//    }
}
